import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Modal, Radio, Select, Space } from 'antd';

import Cron from '@/components/cron';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equRepairRegularPlanAdd,
  equRepairRegularPlanUpdate
} from '@/services/bizApi/shebaodingqijianxiujihuajiekou';
import {
  equInfoGetEquipmentCodeList,
  equInfoGetEquipmentNameList
} from '@/services/bizApi/shebaoxinxijiekou';
import { commonCronTranslate } from '@/services/bizApi/tongyongCronjiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [cronBool, setCronBool] = useState<boolean>(false);
  const [cronValue, setCronValue] = useState<string | undefined>('');
  const cronVal = useRef<string>('');

  const cronText = useRequest(async () => {
    if (!form.getFieldValue('cron')) {
      return;
    }
    const res = await commonCronTranslate({
      cron: form.getFieldValue('cron') as string
    });

    cronVal.current = res?.data as string;
  });
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        dutyUserName: userInfo?.data?.filter((item) => item.id === values?.dutyUserId)?.[0]
          ?.fullName
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? equRepairRegularPlanUpdate(query)
        : equRepairRegularPlanAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);
        cronVal.current = '';
        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData
            });
            cronText.run();
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增定期维修',
          edit: '编辑定期维修',
          detail: '定期维修详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <ProFormSelect
          name="productionSite"
          label="生产站点"
          placeholder="请选择生产站点"
          rules={[{ required: true, message: '请选择生产站点' }]}
          request={async () => {
            return (store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
        />
        <ProFormSelect
          name="processSection"
          label="工艺段"
          placeholder="请选择工艺段"
          rules={[{ required: true, message: '请选择工艺段' }]}
          request={async () => {
            return (store.dict['processSection'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
          onChange={() => {
            form?.setFieldsValue({
              ...form.getFieldsValue,
              equipmentName: undefined,
              equipmentCode: undefined
            });
          }}
        />
        <ProFormSelect
          name="equipmentName"
          label="设备名称"
          placeholder="请选择设备名称"
          dependencies={['processSection']}
          rules={[{ required: true, message: '请选择设备名称' }]}
          request={async ({ processSection }) => {
            if (!processSection) return [];
            const res = await equInfoGetEquipmentNameList({ processSection });
            return (
              res?.data?.map((item) => {
                return {
                  label: item,
                  value: item
                };
              }) || []
            );
          }}
          onChange={() => {
            form?.setFieldsValue({ ...form.getFieldsValue, equipmentCode: undefined });
          }}
        />
        <ProFormSelect
          name="equipmentCode"
          label="设备编号"
          placeholder="请选择设备编号"
          dependencies={['equipmentName']}
          // mode="multiple"
          rules={[{ required: true, message: '请选择设备编号' }]}
          request={async ({ equipmentName }) => {
            if (!equipmentName) return [];
            const res = await equInfoGetEquipmentCodeList({ equipmentName });
            return (
              res?.data?.map((item) => {
                return {
                  label: item,
                  value: item
                };
              }) || []
            );
          }}
        />

        <Form.Item
          label="计划检修周期"
          name="cron"
          rules={[
            {
              required: true,
              message: '请选择计划检修周期'
            }
          ]}
        >
          <Input
            placeholder="请输入计划检修周期"
            onClick={(v) => {
              //@ts-ignore
              setCronValue(v?.target?.value);
              setCronBool(true);
            }}
          />
        </Form.Item>
        <Form.Item label="计划检修周期译文">
          <Input disabled value={cronVal.current} />
        </Form.Item>
        <Form.Item
          label="检修类型"
          name="type"
          rules={[
            {
              required: true,
              message: '请选择检修类型'
            }
          ]}
        >
          <Select
            options={[
              {
                label: '内修',
                value: '内修'
              },
              {
                label: '外修',
                value: '外修'
              }
            ]}
            placeholder="请选择检修类型"
          />
        </Form.Item>
        <Form.Item
          label="负责人"
          name="dutyUserId"
          rules={[
            {
              required: true,
              message: '请选择负责人'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择负责人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Form.Item>
        <Form.Item
          label="检修内容"
          name="content"
          rules={[
            {
              required: true,
              message: '请输入检修内容'
            }
          ]}
        >
          <Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="请输入检修内容" />
        </Form.Item>

        <Form.Item
          label="是否启用"
          name="enabled"
          rules={[
            {
              required: true,
              message: '请选择是否启用'
            }
          ]}
        >
          <Radio.Group>
            <Radio value={true}>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </Form.Item>
      </Form>
      {cronBool && (
        <Modal
          title="Cron表达式"
          open={cronBool}
          width={800}
          footer={null}
          onCancel={() => {
            setCronBool(false);
          }}
        >
          <Cron
            value={cronValue}
            onSuccess={(val: string) => {
              form.setFieldsValue({
                cron: val
              });
              setCronBool(false);
              if (val) {
                cronText.run();
              }
            }}
          />
        </Modal>
      )}
    </Drawer>
  );
};

export default forwardRef(Edit);
